package eop.graham

class StudyController {
	StudyService study

	String currentStudyCriteria = ""
	//TODO this variable is meant to be set in makestudy then used in saveStudy... but value doesn't persist.

	def index = {render (view:"makeStudy")}

	def siteHome = {redirect (url:"/eop.graham") }

	def makeStudy = {
		StudyService s = [:]
		def retList = s.dataSortedBy(params.numerator, params.denominator)
		currentStudyCriteria = params.numerator+"/"+params.denominator
		def expressionLevelList = retList[0..4].collect{it.(params.numerator)/it.(params.denominator)}
		return [status:"Top 5 genes ranked by ${params.numerator}/${params.denominator}\
		<p>${retList[0..4].geneName}", expList:"${expressionLevelList}"]
	}

	def searchStudy = {
		StudyService s = [:]
		def retList = s.studySearch(params.studyGene)
		return [status:"Studies tagged with gene ${params.studyGene}:<p> ${retList}"]
	}

	def saveStudy = {

		def beanToSave = new Study(
				studyName: params.studyName,
				geneName:params.tagName,
				researcher: params.researcher,
				studyCriteria: currentStudyCriteria,
				annotation:params.annotation,
				)
		if (beanToSave.validate()){
			try{
				beanToSave.save(failOnError: true)
				return [status2:"Save successful"]
			}catch(Exception e){
				log.error "Exception saving ${beanToSave}: ${e}"
				return [status2:"Save unsuccessful"]}
		}
		else{
			beanToSave.errors.allErrors.each{log.error "Errors saving ${beanToSave}:${it}" }
			return [status2:"Validation failed: study not saved."]
		}
	}

	def scaffold = true
}